package com.ruoyi.xxljob.admin.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.xxljob.admin.core.model.XxlJobGroup;
import com.ruoyi.xxljob.admin.core.model.XxlJobInfo;
import com.ruoyi.xxljob.admin.core.model.XxlJobUser;
import com.ruoyi.xxljob.admin.core.thread.JobTriggerPoolHelper;
import com.ruoyi.xxljob.admin.core.trigger.TriggerTypeEnum;
import com.ruoyi.xxljob.admin.core.util.I18nUtil;
import com.ruoyi.xxljob.admin.dao.XxlJobGroupDao;
import com.ruoyi.xxljob.admin.dao.XxlJobInfoDao;
import com.ruoyi.xxljob.admin.service.LoginService;
import com.ruoyi.xxljob.admin.service.XxlJobService;
import com.ruoyi.xxljob.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * jobInfo controller
 * 任务相关
 *
 * @author wjialong
 */
@RestController
@RequestMapping("/info")
public class JobInfoController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(JobInfoController.class);

    @Resource
    private XxlJobGroupDao xxlJobGroupDao;
    @Resource
    private XxlJobService xxlJobService;
    @Autowired
    private XxlJobInfoDao xxlJobInfoDao;

    public static List<XxlJobGroup> filterJobGroupByRole(HttpServletRequest request, List<XxlJobGroup> jobGroupList_all) {
        List<XxlJobGroup> jobGroupList = new ArrayList<>();
        if (jobGroupList_all != null && jobGroupList_all.size() > 0) {
            XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
            if (loginUser.getRole() == 1) {
                jobGroupList = jobGroupList_all;
            } else {
                List<String> groupIdStrs = new ArrayList<>();
                if (loginUser.getPermission() != null && loginUser.getPermission().trim().length() > 0) {
                    groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(","));
                }
                for (XxlJobGroup groupItem : jobGroupList_all) {
                    if (groupIdStrs.contains(String.valueOf(groupItem.getId()))) {
                        jobGroupList.add(groupItem);
                    }
                }
            }
        }
        return jobGroupList;
    }

    public static void validPermission(HttpServletRequest request, int jobGroup) {
        XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
        if (!loginUser.validPermission(jobGroup)) {
            throw new RuntimeException(I18nUtil.getString("system_permission_limit") + "[username=" + loginUser.getUsername() + "]");
        }
    }

    /**
     * 获取单个任务的详情
     */
    @RequiresPermissions("xxl-job:info:query")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable int id) {
        return AjaxResult.success(xxlJobInfoDao.loadById(id));
    }

    /**
     * RuoYi 查询任务管理列表
     */
    @RequiresPermissions("xxl-job:info:query")
    @GetMapping("/list")
    public TableDataInfo list(XxlJobInfo xxlJobInfo) {
        startPage();
        List<XxlJobInfo> list = xxlJobService.selectXxlJobInfoList(xxlJobInfo);
        return getDataTable(list);
    }

    /**
     * 新增任务
     *
     * @param jobInfo
     * @return
     */
    @RequiresPermissions("xxl-job:info:add")
    @PostMapping
    public AjaxResult add(@RequestBody XxlJobInfo jobInfo) {
        ReturnT<String> ret = xxlJobService.add(jobInfo);
        if (ret.getCode() == 200) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error(ret.getMsg());
        }
    }

    /**
     * 修改/更新任务
     *
     * @param jobInfo
     * @return
     */
    @PutMapping("/update")
    @RequiresPermissions("xxl-job:info:edit")
    public AjaxResult update(@RequestBody XxlJobInfo jobInfo) {
        ReturnT<String> ret = xxlJobService.update(jobInfo);
        if (ret.getCode() == 200) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error(ret.getMsg());
        }
    }

    /**
     * 删除任务
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @RequiresPermissions("xxl-job:info:remove")
    public AjaxResult remove(@PathVariable int id) {
        return xxlJobService.remove(id);
    }

    /**
     * 停止任务
     *
     * @param id
     * @return
     */
    @RequiresPermissions("xxl-job:info:edit")
    @PostMapping("/stop/{id}")
    public AjaxResult pause(@PathVariable int id) {
        return xxlJobService.stop(id);
    }

    /**
     * 开启任务
     *
     * @param id
     * @return
     */
    @RequiresPermissions("xxl-job:info:edit")
    @PostMapping("/start/{id}")
    public AjaxResult start(@PathVariable int id) {
        return xxlJobService.start(id);
    }

    /**
     * 执行一次
     *
     * @param id
     * @param executorParam
     * @param addressList
     * @return
     */
    @RequiresPermissions("xxl-job:info:edit")
    @PostMapping("/trigger/{id}")
    //@PermissionLimit(limit = false)
    public AjaxResult triggerJob(@PathVariable int id, String executorParam, String addressList) {
        // force cover job param
        if (executorParam == null) {
            executorParam = "";
        }

        JobTriggerPoolHelper.trigger(id, TriggerTypeEnum.MANUAL, -1, null, executorParam, addressList);
        return AjaxResult.success();
    }

    /**
     * 获取下次执行时间
     *
     * @param id
     * @return
     */
    @RequiresPermissions("xxl-job:info:query")
    @RequestMapping("/nextTriggerTime/{id}")
    public AjaxResult nextTriggerTime(@PathVariable int id) {
        return xxlJobService.nextTriggerTime(id);
    }

//    @RequestMapping("/pageList")
//    @ResponseBody
//    public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,
//                                        @RequestParam(required = false, defaultValue = "10") int length,
//                                        int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {
//
//        return xxlJobService.pageList(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author);
//    }

//    @RequestMapping("/nextTriggerTime")
//    @ResponseBody
//    public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) {
//
//        XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
//        paramXxlJobInfo.setScheduleType(scheduleType);
//        paramXxlJobInfo.setScheduleConf(scheduleConf);
//
//        List<String> result = new ArrayList<>();
//        try {
//            Date lastTime = new Date();
//            for (int i = 0; i < 5; i++) {
//                lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
//                if (lastTime != null) {
//                    result.add(DateUtil.formatDateTime(lastTime));
//                } else {
//                    break;
//                }
//            }
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")) + e.getMessage());
//        }
//        return new ReturnT<List<String>>(result);
//
//    }
//    @RequestMapping("/remove")
//    @ResponseBody
//    public ReturnT<String> remove(int id) {
//        return xxlJobService.remove(id);
//    }
//@RequestMapping
//public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "-1") int jobGroup) {
//
//    // 枚举-字典
//    model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values());        // 路由策略-列表
//    model.addAttribute("GlueTypeEnum", GlueTypeEnum.values());                                // Glue类型-字典
//    model.addAttribute("ExecutorBlockStrategyEnum", ExecutorBlockStrategyEnum.values());        // 阻塞处理策略-字典
//    model.addAttribute("ScheduleTypeEnum", ScheduleTypeEnum.values());                        // 调度类型
//    model.addAttribute("MisfireStrategyEnum", MisfireStrategyEnum.values());                    // 调度过期策略
//
//    // 执行器列表
//    List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll();
//
//    // filter group
//    List<XxlJobGroup> jobGroupList = filterJobGroupByRole(request, jobGroupList_all);
//    if (jobGroupList == null || jobGroupList.size() == 0) {
//        throw new XxlJobException(I18nUtil.getString("jobgroup_empty"));
//    }
//
//    model.addAttribute("JobGroupList", jobGroupList);
//    model.addAttribute("jobGroup", jobGroup);
//
//    return "jobinfo/jobinfo.index";
//}


}
